import { generateUniqueId } from "../assets/waws.js"
import axios from "axios"; 
const pendingTasks = new Map();
// background.js
chrome.runtime.onInstalled.addListener(() => {
    console.log('HTML Code Extractor installed.');
});
chrome.runtime.onMessage.addListener(async (request, sender, sendResponse) => {
    if (request.action === "axios") {
        sendResponse({ data: "来自background的数据" });

        const tabId = sender.tab.id;
        const taskId = generateUniqueId(); // 生成唯一任务ID

        pendingTasks.set(taskId, tabId);

        console.log("pendingTasks:",pendingTasks);
        
        let res = null;
        try {
            res = await axios(request.config);
        } catch (error) {
            res = error?.response?.data?.error ?? error;
        }
        // 给content-script发送数据
        const targetTabId = pendingTasks.get(taskId);
        if (targetTabId) {
            // 给content.js发送消息

            chrome.tabs.sendMessage(targetTabId, { action: "responseData", data: res }, function(){
                console.log('发送成功');
                if (chrome.runtime.lastError) {
                    console.log("Message failed:", chrome.runtime.lastError.message);
                }
            });
            pendingTasks.delete(taskId); // 清理存储
        }
    }
});

async function getCurrentTab() {
    let queryOptions = {active: true, currentWindow: true};
    // `tab` will either be a `tabs.Tab` instance or `undefined`.
    let [tab] = await chrome.tabs.query(queryOptions);
    return tab;
}